package com.cxh.rmsq.ui.dialog

import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.database.Cursor
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.text.TextUtils
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import com.cxh.rmsq.R
import com.cxh.rmsq.utils.CustomPermissionUtil
import com.cxh.rmsq.utils.GlideEngine
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.config.SelectModeConfig
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnPermissionsInterceptListener
import com.luck.picture.lib.interfaces.OnRequestPermissionListener
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.luck.picture.lib.permissions.PermissionChecker
import com.luck.picture.lib.permissions.PermissionConfig
import com.luck.picture.lib.permissions.PermissionResultCallback
import java.util.Arrays

/**
 * author：haomeng
 * on：3/16/21
 * created by：诚信华
 * describe:
 */
class PhotoDialog : Dialog {
    var mContext: Context
    var i: Int = 1
    var x: Int = 3
    var y: Int = 3
    var enableCrop: Boolean = false
    var pictureSelector: PictureSelector? = null


    constructor(context: Context, themeResId: Int) : super(context, themeResId) {
        this.mContext = context
    }


    constructor(context: Context, enableCrop: Boolean, themeResId: Int) : super(context,
        themeResId) {
        this.mContext = context
        this.enableCrop = enableCrop
    }

    constructor(context: Context, enableCrop: Boolean, x: Int, y: Int, themeResId: Int) : super(
        context,
        themeResId) {
        this.mContext = context
        pictureSelector = PictureSelector.create(mContext as Activity)
        this.enableCrop = enableCrop
        this.x = x
        this.y = y
    }

    constructor(context: Context, themeResId: Int, i: Int) : super(context, themeResId) {
        this.mContext = context
        this.i = i
    }
    constructor(context: Context, themeResId: Int, i: Int,enableCrop: Boolean,) : super(context, themeResId) {
        this.mContext = context
        this.i = i
        this.enableCrop = enableCrop
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        var view: View = LayoutInflater.from(mContext).inflate(R.layout.dialog_photo, null)
        setContentView(view)
        pictureSelector = PictureSelector.create(mContext as Activity)
        var layoutParams: ViewGroup.LayoutParams = view.layoutParams
        layoutParams.width = mContext.resources.displayMetrics.widthPixels
        view.layoutParams = layoutParams
        window?.setGravity(Gravity.BOTTOM)
        window?.setWindowAnimations(R.style.BottomDialog_Animation)
        val display = (mContext as Activity).windowManager.defaultDisplay
        //设置弹框的高为屏幕的一半宽是屏幕的宽
        val lp = window?.attributes
        lp?.width = display.getWidth()//设置宽度
        lp?.height = (display.getHeight() * 0.7).toInt() //设置宽度
        getWindow()?.setAttributes(lp);
        view.findViewById<TextView>(R.id.photo_select_btn_image).setOnClickListener {
            transferCamera()
            dismiss()
        }
        view.findViewById<TextView>(R.id.photo_select_btn_take).setOnClickListener {
            transferPhoto()
            dismiss()
        }
        view.findViewById<TextView>(R.id.photo_select_btn_cancel).setOnClickListener {
            dismiss()
        }
    }


    public fun transferPhoto() {
        pictureSelector!!.openGallery(SelectMimeType.ofImage()) //全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
            .setImageEngine(GlideEngine.createGlideEngine())// 图片加载引擎 需要 implements ImageEngine接口
            .setMaxSelectNum(i) // 最大图片选择数量 int
            .setMinSelectNum(0) // 最小选择数量 int
            .setImageSpanCount(4) // 每行显示个数 int
            .setSelectionMode(SelectModeConfig.MULTIPLE) // 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
            .isDisplayCamera(true) // 是否显示拍照按钮 true or false
            .setCameraImageFormat(PictureMimeType.PNG) // 拍照保存图片格式后缀,默认jpeg
//            .isZoomAnim(true) // 图片列表点击 缩放效果 默认true
//            .isEnableCrop(enableCrop)
//            .isCompress(true)
//            .withAspectRatio(x, y) // int 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
            .isGif(false)
            .isMaxSelectEnabledMask(true)
            .isOriginalControl(true)
            .isPageStrategy(true)
//            .circleDimmedLayer(false) // 是否圆形裁剪 true or false
//            .minimumCompressSize(100) // 小于100kb的图片不压缩
//            .synOrAsy(true) //同步true或异步false 压缩 默认同步
//            .isDragFrame(false) // 是否可拖动裁剪框(固定)
            .setPermissionsInterceptListener(object : OnPermissionsInterceptListener {
                override fun requestPermission(
                    fragment: Fragment,
                    permissionArray: Array<String>,
                    call: OnRequestPermissionListener
                ) {
                    val permissionInfoDialog = Dialog(fragment.requireActivity())
                    //应用上架要求添加权限使用说明
                    var permissionInfoTitle = ""
                    var permissionInfoContent = ""
                    if (Arrays.equals(
                            permissionArray,
                            PermissionConfig.getReadPermissionArray(
                                fragment.context,
                                SelectMimeType.ofImage()
                            )
                        )
                    ) {
                        permissionInfoTitle =
                            mContext.resources.getString(R.string.permission_info_title_storage)
                        permissionInfoContent =
                            mContext.resources.getString(R.string.permission_info_content_storage)
                    } else if (Arrays.equals(permissionArray, PermissionConfig.CAMERA)) {
                        permissionInfoTitle =
                            mContext.resources.getString(R.string.permission_info_title_camera)
                        permissionInfoContent =
                            mContext.resources.getString(R.string.permission_info_content_camera)
                    }
                    if (!TextUtils.isEmpty(permissionInfoTitle) && !TextUtils.isEmpty(
                            permissionInfoContent
                        )
                    ) {
                        CustomPermissionUtil.showPermissionInfo(
                            fragment.activity,
                            permissionInfoDialog,
                            permissionInfoTitle,
                            permissionInfoContent
                        )
                    }

                    //此处使用图片选择框架的权限申请
                    PermissionChecker.getInstance().requestPermissions(
                        fragment,
                        permissionArray,
                        object : PermissionResultCallback {
                            override fun onGranted() {
                                permissionInfoDialog.dismiss()
                                call.onCall(permissionArray, true)
                            }

                            override fun onDenied() {
                                permissionInfoDialog.dismiss()
                                call.onCall(permissionArray, false)
                            }
                        })
                }

                override fun hasPermissions(
                    fragment: Fragment,
                    permissionArray: Array<String>
                ): Boolean {
                    return PermissionChecker.isCheckSelfPermission(
                        fragment.context,
                        permissionArray
                    )
                }
            })
            .setPermissionDeniedListener { fragment, permissionArray, requestCode, call -> //权限拒绝，弹出去设置弹窗，点击设置跳转到应用权限系统设置页面
                var permissionSetContent = ""
                if (Arrays.equals(
                        permissionArray,
                        PermissionConfig.getReadPermissionArray(
                            fragment.context,
                            SelectMimeType.ofImage()
                        )
                    )
                ) {
                    permissionSetContent = mContext.resources.getString(R.string.permission_set_storage)
                } else if (Arrays.equals(permissionArray, PermissionConfig.CAMERA)) {
                    permissionSetContent = mContext.resources.getString(R.string.permission_set_camera)
                }
                if (!TextUtils.isEmpty(permissionSetContent)) {
                    CustomPermissionUtil.showPermissionSet(
                        fragment.activity,
                        permissionSetContent,
                        ArrayList(Arrays.asList(*permissionArray))
                    ) { call.onCall(true) }
                }
            }
            .forResult(object : OnResultCallbackListener<LocalMedia> {
                override fun onResult(result: java.util.ArrayList<LocalMedia>?) {
                    if (result != null) {
                        val images: MutableList<String> = ArrayList()
                        for (localMedia in result) {
                            var path = localMedia.realPath.toString()
//                            if (enableCrop) {
//                                localMedia.isCut()
//                                path = localMedia.cutPath
//                            }
                            if (path.contains("content://")) {
                                val imgPath = getPath(path)
                                images.add(imgPath)
                            } else {
                                images.add(path)
                            }
                        }
                        if (listener != null) {
                            listener?.onPhotoPathResult(images)
                        }
                    }
                }

                override fun onCancel() {
                }

            })
    }

    private fun transferCamera() {
        //拍照
        pictureSelector!!.openCamera(SelectMimeType.ofImage())
//            .maxSelectNum(i) // 最大图片选择数量 int
//            .minSelectNum(0) // 最小选择数量 int
//            .imageSpanCount(4) // 每行显示个数 int
//            .selectionMode(SelectModeConfig.MULTIPLE) // 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
//            .isPreviewVideo(true) // 是否可预览图片 true or false
//            .isCamera(true) // 是否显示拍照按钮 true or false
//            .imageFormat(PictureMimeType.PNG) // 拍照保存图片格式后缀,默认jpeg
//            .isZoomAnim(true) // 图片列表点击 缩放效果 默认true
//            .isEnableCrop(enableCrop) // 是否裁剪 true or false
//            .isCompress(true)
//            .withAspectRatio(x, y) // int 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
//            .isGif(true) // 是否显示gif图片 true or false
//            .circleDimmedLayer(false) // 是否圆形裁剪 true or false
//            .isPreviewEggs(false) // 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false
//            .minimumCompressSize(100) // 小于100kb的图片不压缩
//            .synOrAsy(true) //同步true或异步false 压缩 默认同步
//            .isDragFrame(false) // 是否可拖动裁剪框(固定)
            .setPermissionsInterceptListener(object : OnPermissionsInterceptListener {
                override fun requestPermission(
                    fragment: Fragment,
                    permissionArray: Array<String>,
                    call: OnRequestPermissionListener
                ) {
                    val permissionInfoDialog = Dialog(fragment.requireActivity())
                    //应用上架要求添加权限使用说明
                    var permissionInfoTitle = ""
                    var permissionInfoContent = ""
                    if (Arrays.equals(
                            permissionArray,
                            PermissionConfig.getReadPermissionArray(
                                fragment.context,
                                SelectMimeType.ofImage()
                            )
                        )
                    ) {
                        permissionInfoTitle =
                            mContext.resources.getString(R.string.permission_info_title_storage)
                        permissionInfoContent =
                            mContext.resources.getString(R.string.permission_info_content_storage)
                    } else if (Arrays.equals(permissionArray, PermissionConfig.CAMERA)) {
                        permissionInfoTitle =
                            mContext.resources.getString(R.string.permission_info_title_camera)
                        permissionInfoContent =
                            mContext.resources.getString(R.string.permission_info_content_camera)
                    }
                    if (!TextUtils.isEmpty(permissionInfoTitle) && !TextUtils.isEmpty(
                            permissionInfoContent
                        )
                    ) {
                        CustomPermissionUtil.showPermissionInfo(
                            fragment.activity,
                            permissionInfoDialog,
                            permissionInfoTitle,
                            permissionInfoContent
                        )
                    }

                    //此处使用图片选择框架的权限申请
                    PermissionChecker.getInstance().requestPermissions(
                        fragment,
                        permissionArray,
                        object : PermissionResultCallback {
                            override fun onGranted() {
                                permissionInfoDialog.dismiss()
                                call.onCall(permissionArray, true)
                            }

                            override fun onDenied() {
                                permissionInfoDialog.dismiss()
                                call.onCall(permissionArray, false)
                            }
                        })
                }

                override fun hasPermissions(
                    fragment: Fragment,
                    permissionArray: Array<String>
                ): Boolean {
                    return PermissionChecker.isCheckSelfPermission(
                        fragment.context,
                        permissionArray
                    )
                }
            })
            .setPermissionDeniedListener { fragment, permissionArray, requestCode, call -> //权限拒绝，弹出去设置弹窗，点击设置跳转到应用权限系统设置页面
                var permissionSetContent = ""
                if (Arrays.equals(
                        permissionArray,
                        PermissionConfig.getReadPermissionArray(
                            fragment.context,
                            SelectMimeType.ofImage()
                        )
                    )
                ) {
                    permissionSetContent = mContext.resources.getString(R.string.permission_set_storage)
                } else if (Arrays.equals(permissionArray, PermissionConfig.CAMERA)) {
                    permissionSetContent = mContext.resources.getString(R.string.permission_set_camera)
                }
                if (!TextUtils.isEmpty(permissionSetContent)) {
                    CustomPermissionUtil.showPermissionSet(
                        fragment.activity,
                        permissionSetContent,
                        ArrayList(Arrays.asList(*permissionArray))
                    ) { call.onCall(true) }
                }
            }
            .forResult(object : OnResultCallbackListener<LocalMedia> {
                override fun onResult(result: java.util.ArrayList<LocalMedia>?) {
                    if (result != null) {
                        val images: MutableList<String> = ArrayList()
                        for (localMedia in result) {
                            var path = localMedia.path.toString()
//                            if (enableCrop) {
//                                localMedia.isCut()
//                                path = localMedia.cutPath
//                            }
                            if (path.contains("content://")) {
                                val imgPath = getPath(path)
                                images.add(imgPath)
                            } else {
                                images.add(path)
                            }
                        }
                        if (listener != null) {
                            listener?.onCameraPathResult(images)
                        }
                    }
                }

                override fun onCancel() {
                }
            })
    }

    var listener: OnClickListener? = null
    fun setOnClickListener(listener: OnClickListener) {
        this.listener = listener
    }

    interface OnClickListener {
        fun onPhotoPathResult(images: MutableList<String>)
        fun onCameraPathResult(images: MutableList<String>)
    }


    private fun getPath(path: String): String {
        if (!path.isEmpty()) {
            val uri = Uri.parse(path)
            val proj =
                arrayOf(MediaStore.Images.Media.DATA)
            val actualimagecursor: Cursor =
                context.contentResolver.query(uri, proj, null, null, null)!!
            val actual_image_column_index =
                actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
            actualimagecursor.moveToFirst()
            val img_path = actualimagecursor.getString(actual_image_column_index)
            return img_path
        }
        return ""
    }
}